import Vue from 'vue'
import VueRouter from 'vue-router'
import { changeTitle } from "@/utils/index.js"
import cookies from "@/utils/util.cookies.js"
import store from '@/store/index'
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import routes from "./routers.js"
// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})


router.beforeEach(async (to, from, next) => {
  await store.dispatch('admin/page/isLoaded')
  // 进度条
  NProgress.start()
  // store.commit('admin/search/set', false)
  if (to.matched.some(r => r.meta.auth)) {
    const token = cookies.get('token') // || 'test'
    if (token && token !== 'undefined') {
      next()
    } else {
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
      NProgress.done()
      next()
    }
  } else {
    next()
  }
})

router.afterEach(to => {
  NProgress.done()
  store.dispatch('admin/page/open', to)
  changeTitle(to.meta.title)
})


export default router